package com.example.tys.baseapplication;

import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import android.os.Debug;
import android.os.Environment;

import com.example.tys.baseapplication.DataModel.greendao.gen.DaoMaster;
import com.example.tys.baseapplication.DataModel.greendao.gen.DaoSession;
import com.example.tys.baseapplication.NetModel.okhttp.OkHttpClientManger;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * Created by tys on 2017/9/30.
 */

public class MyApp extends Application {
    private static MyApp mInstance;
    private WeakReference<DaoSession> mDaoSessionRef;

    @Override
    public void onCreate() {
        super.onCreate();
//        File f = new File(Environment.getExternalStorageDirectory(), "trac_app");
//        Debug.startMethodTracing(f.getAbsolutePath());
        mInstance = this;
        initData();
        initNet();
    }

    private void initNet() {
         OkHttpClientManger.init(getApplicationContext());
    }

    public static MyApp getInstance() {
        return mInstance;
    }

    private void initData() {
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this, "test-db", null);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        DaoMaster mDaoMaster = new DaoMaster(db);
        mDaoSessionRef = new WeakReference<>(mDaoMaster.newSession());
    }

    public DaoSession getDaoSession() {
        DaoSession daoSession = mDaoSessionRef.get();
        if(daoSession == null){
            initData();
            return mDaoSessionRef.get();
        }
        return daoSession;
    }
}
